package com.zx;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zx.annotation.DataConfig;
import com.zx.enums.DataType;
import com.zx.exception.DataParseException;
import com.zx.process.DataConfigProcess;
import com.zx.process.impl.TextDataConfigProcess;
/**
 * @Project: dataParse-core
 * @Title: ParseFactory
 * @Description: 解析器工程
 * @author: xue.zhang
 * @date: 2018年2月12日下午4:28:53
 * @company: yooli
 * @Copyright: Copyright (c) 2017
 * @version v1.0
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class ParseFactory {
	
	private static Logger logger = LoggerFactory.getLogger(ParseFactory.class);
	
	/** 保存实例化之后的解析器 */
	private static Map<String, DataConfigProcess> dataMapper = new ConcurrentHashMap<String, DataConfigProcess>();
	
	/* ***********************  1. 注册类的解析器    *********************************************/
	public static DataConfigProcess register(String classFullName) throws Exception {
		try {
			Class<?> clazz = Class.forName(classFullName);
			return register(clazz);
		} catch (Exception e) {
			throw e;
		}
	}
	
	public static <T> DataConfigProcess<T> register(Class<T> clazz) throws Exception {
		try {
			DataConfig dataConfig = clazz.getAnnotation(DataConfig.class);
			DataType dataType = dataConfig.dataType();
			DataConfigProcess<T> dataConfigProcess = null;
			if(dataType.equals(DataType.TEXT)) {
				dataConfigProcess = new TextDataConfigProcess(clazz);
			} else if(dataType.equals(DataType.EXCEL)) {
				throw new DataParseException("暂不支持 Excel 格式的文件解析");
			} else if(dataType.equals(DataType.BIN)) {
				throw new DataParseException("暂不支持 二进制 格式的文件解析");
			} 
			dataMapper.put(clazz.getName(), dataConfigProcess);
			return dataMapper.get(clazz.getName());
		} catch (Exception e) {
			logger.error("模板类【" + clazz + "】注册失败", e);
			throw e;
		}
	}
	
	/* ***********************  2. 注销类的解析器    *********************************************/
	public static void unRegister(String classFullName) {
		dataMapper.remove(classFullName);
	}
	
	public static <T> void unRegister(Class<T> clazz) {
		unRegister(clazz.getName());
	}
	
	/* ***********************  3. 获得类的解析器    *********************************************/
	public static DataConfigProcess<?> getMapper(String classFullName) {
		return dataMapper.get(classFullName);
	}
	
	public static <T> DataConfigProcess<T> getMapper(Class<T> clazz) {
		return dataMapper.get(clazz.getName());
	}
}
